<template>
    <div>
        <el-row :gutter="20">
            <el-col :span="8">
                <el-card shadow="hover" class="mgb20" style="height:252px;">
                    <div class="user-info">
                        <img :src="headLogo" class="user-avator" alt />
                        <div class="user-info-cont">
                            <div class="user-info-name">{{name}}</div>
                            <div>{{role}}</div>
                        </div>
                    </div>
                    <div class="user-info-list">
                        上次登录时间：
                        <span>{{loginTime}}</span>
                    </div>
                    <div class="user-info-list">
                        上次登录系统：
                        <span>{{os}}</span>
                    </div>
                    <!--<div class="user-info-list">
                        上次登录浏览器：
                        <span>{{browser}}</span>
                    </div>-->
                </el-card>
                <el-card shadow="hover" style="height:252px;">
                    <div slot="header" class="clearfix">
                        <span>设备详情</span>
                    </div>CPU
                    <el-progress :percentage="cpuLoad" color="#42b983"></el-progress>内存
                    <el-progress :percentage="memoryLoad" color="#f1e05a"></el-progress>
                </el-card>
            </el-col>
            <el-col :span="16">
                <el-row :gutter="20" class="mgb20">
                    <el-col :span="8">
                        <el-card shadow="hover" :body-style="{padding: '0px'}">
                            <div class="grid-content grid-con-1">
                                <i class="el-icon-lx-people grid-con-icon"></i>
                                <div class="grid-cont-right">
                                    <div class="grid-num">{{userCount}}</div>
                                    <div>用户人数</div>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="8">
                        <el-card shadow="hover" :body-style="{padding: '0px'}">
                            <div class="grid-content grid-con-2">
                                <i class="el-icon-lx-notice grid-con-icon"></i>
                                <div class="grid-cont-right">
                                    <div class="grid-num">{{dayCount}}</div>
                                    <div>当天用户消息</div>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="8">
                        <el-card shadow="hover" :body-style="{padding: '0px'}">
                            <div class="grid-content grid-con-3">
                                <i class="el-icon-lx-goods grid-con-icon"></i>
                                <div class="grid-cont-right">
                                    <div class="grid-num">{{dayCountUser}}</div>
                                    <div>当天当前用户消息</div>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
                <el-card shadow="hover" style="height:403px;">
                    <div slot="header" class="clearfix">
                        <span>用户消息</span>
                        <el-button style="float: right; padding: 3px 0" type="text" @click="handleEnterThing">添加</el-button>
                    </div>
                    <el-table :show-header="false" :data="todoList" style="width:100%;">
                        <el-table-column width="40">
                            <template slot-scope="scope">
                                <el-checkbox v-model="scope.row.status"></el-checkbox>
                            </template>
                        </el-table-column>
                        <el-table-column>
                            <template slot-scope="scope">
                                <div
                                    class="todo-item"
                                    :class="{'todo-item-del': scope.row.status}"
                                >{{scope.row.title}}</div>
                            </template>
                        </el-table-column>
                        <el-table-column width="60">
                            <template>
                                <i class="el-icon-edit"></i>
                                <i class="el-icon-delete"></i>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="12">
                <el-card shadow="hover">
                    <schart ref="bar" class="schart" canvasId="bar" :options="options"></schart>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card shadow="hover">
                    <schart ref="line" class="schart" canvasId="line" :options="options2"></schart>
                </el-card>
            </el-col>
        </el-row>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
            <el-form ref="form" :model="form" :rules="rules" label-width="70px">
                <el-form-item label="标题" prop="title" >
                    <el-input v-model="form.title" ></el-input>
                </el-form-item>
                <el-form-item label="类型" >
                    <el-select v-model="form.typeArr" multiple placeholder="请选择">
                        <el-option label="浏览器端" value="1"></el-option>
                        <el-option label="微信端" value="2"></el-option>
                        <el-option label="APP端" value="3"></el-option>
                        <el-option label="短信" value="4"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="对象" >
                    <el-select v-model="form.userIdArr" multiple placeholder="请选择">
                        <el-option
                                v-for="item in form.users"
                                :key="item.id"
                                :label="item.userName"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import Schart from 'vue-schart';
import moment from 'moment';

import { sysLoginLogInfo,getHeadImage } from '../../api/sysLoginLog';
import { sysLogCountDate,sysLogCount } from '../../api/sysLog';
import { systemInfo,sysUserList } from '../../api/sysUser';
import { saveSysMessage } from '../../api/sysMessage';

import bus from '../common/bus';

export default {
    name: 'dashboard',
    data() {
        return {
            name: localStorage.getItem('ms_username'),
            headLogo: localStorage.getItem('headLogo'),
            loginTime:'1970-01-01 00:00:00',
            os:'',
            browser:'',
            cpuLoad:0.0,
            memoryLoad:0.0,
            userCount:0,
            dayCount:0,
            dayCountUser:0,
            todoList: [],
            editVisible:false,
            form:{
                userIdArr:[],
                users:[]
            },
            options: {
                type: 'bar',
                title: {
                    text: '最近系统使用日志（按天）'
                },
                xRorate: 25,
                labels: [],
                datasets: [{
                    label:'天',
                    data:[]
                }]
            },
            options2: {
                type: 'line',
                title: {
                    text: '系统使用日志（按模块）'
                },
                labels: [],
                datasets: [{
                    label:'模块',
                    data:[]
                }]
            },
            rules: {
                title: [
                    { required: true, message: '请输入名称', trigger: 'blur' }
                ]
            }
        };
    },
    components: {
        Schart
    },
    computed: {
        role() {
            return this.name === 'admin' ? '超级管理员' : '普通用户';
        }
    },
    created() {
        this.handleListener();
        // this.changeDate();
        getHeadImage({url:"wwww.baidu.com"}).then(res => {
            let blob = new Blob([res]);
            let url = window.URL.createObjectURL(blob);
            //console.log(blob)
            //this.headLogo = url
        });
        // 上次登录信息
        sysLoginLogInfo({loginName:this.name}).then(res => {
            this.loginTime = moment(res.lastLog.loginTime).format('YYYY-MM-DD HH:mm:ss');
            this.os = res.lastLog.os;
            this.browser = res.lastLog.browser;
        });
        // 系统使用情况
        systemInfo().then(res => {
            if (res.code == 0) {
                this.cpuLoad = parseFloat(res.cpuLoad);
                this.memoryLoad = parseFloat(res.memoryLoad);
                this.userCount = res.count;
                this.dayCount = res.dayCount;
                this.dayCountUser = res.dayCountUser;
                // 消息数
                this.todoList = res.messageList
            }
        });
        // 按天统计
        sysLogCountDate().then(res => {
            if (res.code == 0 && res.sysLogList != null && res.sysLogList.length > 0) {
                let nameArr = [];
                let valueArr = [];
                res.sysLogList.forEach((item, index) => {
                    nameArr.push(item.dateStr);
                    valueArr.push(item.useNum);
                });
                this.options.labels = nameArr;
                this.options.datasets[0].data = valueArr;
            }
        });
        // 按模块统计
        sysLogCount().then(res => {
            if (res.code == 0 && res.sysLogList != null && res.sysLogList.length > 0) {
                let nameArr = [];
                let valueArr = [];
                res.sysLogList.forEach((item, index) => {
                    nameArr.push(item.operation);
                    valueArr.push(item.useNum);
                });
                this.options2.labels = nameArr;
                this.options2.datasets[0].data = valueArr;
            }
        });
    },
    activated() {
        this.handleListener();
    },
    deactivated() {
        window.removeEventListener('resize', this.renderChart);
        bus.$off('collapse', this.handleBus);
    },
    methods: {
        handleEnterThing() {
            this.editVisible = true;
            // 查询当前所有用户
            sysUserList().then(res => {
                if (res.code == 0) {
                    this.form.users = res.sysUserList
                }
            });
            this.$nextTick(()=>{
                this.$refs['form'].clearValidate();
            })
        },
        saveEdit() {
            // ajax提交至后台
            this.$refs['form'].validate((valid) => {
                if (!valid) {
                    console.log('error submit!!');
                    return false;
                }
                let typeArr = this.form.typeArr;
                if (typeArr == null || typeArr.length <= 0) {
                    this.$message.error(`请选择类型`);
                    return false;
                }
                if (typeArr != null && typeArr.length > 0) {
                    this.form.type = typeArr.join(",");
                }
                let userIdArr = this.form.userIdArr;
                if (userIdArr == null || userIdArr.length <= 0) {
                    this.$message.error(`请选择对象`);
                    return false;
                }
                if (userIdArr != null && userIdArr.length > 0) {
                    this.form.userIds = userIdArr.join(",");
                }
                saveSysMessage(this.form).then(res => {
                    if (res.code == 0) {
                        this.editVisible = false;
                        this.$message.success(`修改成功`);
                    } else {
                        this.$message.error(res.msg);
                        return false;
                    }
                });
            });
        },
        handleListener() {
            bus.$on('collapse', this.handleBus);
            // 调用renderChart方法对图表进行重新渲染
            window.addEventListener('resize', this.renderChart);
        },
        handleBus(msg) {
           setTimeout(() => {
                this.renderChart();
            }, 200);
        },
        renderChart() {
            this.$refs.bar.renderChart();
            this.$refs.line.renderChart();
        }
    }
};
</script>


<style scoped>
.el-row {
    margin-bottom: 20px;
}

.grid-content {
    display: flex;
    align-items: center;
    height: 100px;
}

.grid-cont-right {
    flex: 1;
    text-align: center;
    font-size: 14px;
    color: #999;
}

.grid-num {
    font-size: 30px;
    font-weight: bold;
}

.grid-con-icon {
    font-size: 50px;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
    color: #fff;
}

.grid-con-1 .grid-con-icon {
    background: rgb(45, 140, 240);
}

.grid-con-1 .grid-num {
    color: rgb(45, 140, 240);
}

.grid-con-2 .grid-con-icon {
    background: rgb(100, 213, 114);
}

.grid-con-2 .grid-num {
    color: rgb(45, 140, 240);
}

.grid-con-3 .grid-con-icon {
    background: rgb(242, 94, 67);
}

.grid-con-3 .grid-num {
    color: rgb(242, 94, 67);
}

.user-info {
    display: flex;
    align-items: center;
    padding-bottom: 20px;
    border-bottom: 2px solid #ccc;
    margin-bottom: 20px;
}

.user-avator {
    width: 120px;
    height: 120px;
    border-radius: 50%;
}

.user-info-cont {
    padding-left: 50px;
    flex: 1;
    font-size: 14px;
    color: #999;
}

.user-info-cont div:first-child {
    font-size: 30px;
    color: #222;
}

.user-info-list {
    font-size: 14px;
    color: #999;
    line-height: 25px;
}

.user-info-list span {
    margin-left: 70px;
}

.mgb20 {
    margin-bottom: 20px;
}

.todo-item {
    font-size: 14px;
}

.todo-item-del {
    text-decoration: line-through;
    color: #999;
}

.schart {
    width: 100%;
    height: 300px;
}
</style>
